package com.md.mainpage.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.living.filedownloader.ui.audiosel.TasksSelectActivity
import com.living.player.BottomPlayerFragment
import com.living.player.PlayUtils
import com.living.player.event.EventPlayNewData
import com.md.basedpc.base.BaseActivity
import com.md.basedpc.log.Log
import com.md.basedpc.routerservice.NotifyService
import com.md.datastore.MysaveAlbumManager
import com.md.livingwidget.navigation.PHNavigationBar
import com.md.livingwidget.toast.PHToast
import com.md.mainpage.Constants2
import com.md.mainpage.R
import com.md.mainpage.adapter.AlbumAdapter
import com.md.mainpage.databinding.ActivityAlbumBinding
import com.md.mainpage.interfaces.AlbumContract
import com.md.mainpage.presenter.AlbumPresenter
import com.md.mainpage.utils.Utils
import com.md.network.api.Album
import com.md.network.api.Audio
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

@Route(path = "/album2/album")
class AlbumActivity : BaseActivity(), PHNavigationBar.OnBarClickListener, AlbumContract.View , AlbumAdapter.ItemClick{
    @JvmField
    @Autowired(name = "ALBUM_ALBUM_ID")
    var albumId: Int = -1

    private lateinit var binding: ActivityAlbumBinding
    private lateinit var navBar: PHNavigationBar
    private lateinit var tvTitle: TextView
    private lateinit var ivSave: ImageView
    private lateinit var ivDownload: ImageView
    private lateinit var ivShare: ImageView
    private lateinit var recAudio: RecyclerView
    private lateinit var ivAlbumCover: ImageView
    private lateinit var tvAlbumTitle: TextView
    private lateinit var tvAuthor: TextView
    private lateinit var tvProfile: TextView
    private lateinit var albumAdapter: AlbumAdapter
    private var mPrestner = AlbumPresenter()
    private var currentAlbum: Album? = null
    private var isSaved=false//当前专辑是否被收藏了
    private var isFirstPlay=true;//是否第一次播放，第一次播放跳转播放页面，否则不跳转

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityAlbumBinding.inflate(LayoutInflater.from(this))
        setContentView(binding.root)
        ARouter.getInstance().inject(this)
        EventBus.getDefault().register(this)
        initData()
        initNav()
        initView()
        initPlayer()
        requestData()
        setStatusBarColor(true, resources.getColor(R.color.maincolor_578D7B))
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        mPrestner.detachView()
    }

    @Subscribe
    public fun onEvent( event: EventPlayNewData) {
        event?.audio?.let {
            albumAdapter.setCurPlayAudio (it)
        }
    }

    private fun initData() {
        if (albumId <= 0) {
            var sAlbumId = intent.getStringExtra(Constants2.ALBUM_ID)
            try {
                albumId = (sAlbumId?.toInt() as Int)
            } catch (error: Exception) {
                error.printStackTrace()
            }
        }
        mPrestner.attachView(this)
    }

    private fun initNav() {
        navBar = binding.navBar
        navBar.toolbar.setBackgroundColor(resources.getColor(R.color.maincolor_578D7B))
        navBar.root.setBackgroundColor(resources.getColor(R.color.maincolor_578D7B))
        navBar.left1Imgback.apply {
            setImageResource(R.drawable.white_common_back)
            setOnClickListener {
                this@AlbumActivity.finish()
            }
        }
        tvTitle = navBar.centerTvTitle
        tvTitle.apply {
            text = getString(R.string.main_album)
            setTextColor(resources.getColor(R.color.maincolor_white))
        }
        ivSave = navBar.right1Btn
        isSaved = MysaveAlbumManager.getIns().getAlbumDBById(albumId.toString()) !=null
        ivSave.apply {
            visibility = View.VISIBLE
            setImageDrawable(resources.getDrawable(R.drawable.main_save))
            if (isSaved){
                setColorFilter(ContextCompat.getColor(context, R.color.maincolor_ff3333), android.graphics.PorterDuff.Mode.SRC_IN)
            }else{
                setColorFilter(ContextCompat.getColor(context, R.color.white), android.graphics.PorterDuff.Mode.SRC_IN)
            }
            setOnClickListener {
                if(isSaved){
                    if (MysaveAlbumManager.getIns().deleteAlbumById(albumId.toString())){
                        setColorFilter(ContextCompat.getColor(context, R.color.white), android.graphics.PorterDuff.Mode.SRC_IN)
                        ARouter.getInstance().navigation(NotifyService::class.java).selfAlbumUpdateSuc(0x2)// 收藏的专辑，目前传的值还没用
                        PHToast.showSingleToast(this@AlbumActivity,getString(R.string.main_delete_suc))
                        isSaved = false
                    }
                }else{
                    if (MysaveAlbumManager.getIns().saveAlbum(currentAlbum)){
                        setColorFilter(ContextCompat.getColor(context, R.color.maincolor_ff3333), android.graphics.PorterDuff.Mode.SRC_IN)
                        ARouter.getInstance().navigation(NotifyService::class.java).selfAlbumUpdateSuc(0x2)
                        PHToast.showSingleToast(this@AlbumActivity,getString(R.string.main_save_suc))
                        isSaved = true
                    }
                }
            }
        }
        ivDownload = navBar.right2Btn
        ivDownload.apply {
            visibility = View.VISIBLE
            setImageDrawable(resources.getDrawable(R.drawable.main_download))
            setOnClickListener(View.OnClickListener {
                TasksSelectActivity.intentTo(context, albumAdapter?.album)
            })
        }
        ivShare = navBar.right3Btn
        ivShare.apply {
            visibility = View.GONE
            setImageDrawable(resources.getDrawable(R.drawable.main_share))
        }
    }

    private fun initView() {
        recAudio = binding.recAudio
        ivAlbumCover = binding.ivAlbumCover
        tvAlbumTitle = binding.tvAlbumTitle
        tvAuthor = binding.tvAuthor
        tvProfile = binding.tvProfile

        recAudio = binding.recAudio
        recAudio.layoutManager = LinearLayoutManager(this)
        albumAdapter = AlbumAdapter(this, this,ArrayList())
        recAudio.adapter = albumAdapter
    }

    private fun initPlayer() {
        var transaction = supportFragmentManager.beginTransaction()
        var fragment = BottomPlayerFragment()
        transaction.add(R.id.lltPlayer, fragment)
        transaction.commit()
    }

    private fun requestData() {
        mPrestner.getAlbum(albumId = albumId)
    }

    override fun onBarLeft1Back(v: View?) {
    }

    override fun onBarRight2Btn(v: View?) {
    }

    override fun onBarRight1Btn(v: View?) {
    }

    override fun onBarRight3Btn(v: View?) {
    }

    override fun onBarLeft2Back(v: View?) {
    }

    override fun onBarRight1Tv(v: View?) {
    }

    override fun showAlbumInfo(album: Album?) {
        currentAlbum = album
        Glide.with(this)
                .load(album?.coverUrl)
                .apply(RequestOptions.bitmapTransform(RoundedCorners(10))) //用这行设置圆角似乎高要写死，否则高度好像变成了match_parent
                .into(ivAlbumCover)
        tvAlbumTitle.text = album?.name
        tvAuthor.text = album?.author
        tvProfile.text = album?.desc

        var datas = ArrayList<Audio> ()
        var blankAudio = Audio("","","","",false,"","") //第一条数据给了「播放全部」item, 这种实现不优雅，后续改成插入header
        datas.add(blankAudio)
        datas.addAll(album?.audios!!)
        albumAdapter.setData(album, datas)

        //如果是每日必听，就播放今日份的音频
        currentAlbum?.todayAudio?.let {
            it.albumId = currentAlbum!!.id
            Utils.fillAudioData(currentAlbum!!)
            PlayUtils.PlayDailyAudio(this,currentAlbum!!.audios,it)
        }
        Log.e(album.toString())
    }

    override fun showError(errorMsg: String) {
        Log.e(errorMsg)
    }

    override fun onItemClick(album: Album, curAudio: Audio) {
        if(isFirstPlay){
            isFirstPlay = false
            PlayUtils.intentTo(this, album, curAudio)
        }else{
            PlayUtils.playAudio(this,curAudio)
        }
    }
}